import time
from py2neo import Graph
from neobolt.exceptions import AuthError


def get_neo4j_connect(
        url: str, username: str, password: str, retry: bool = False,
        retry_interval: int = 0
):
    """
    获取neo4j的一个数据连接
    :param url: neo4j连接地址
    :param username: neo4j用户名
    :param password: neo4j密码
    :param retry: 是否重复进行尝试(阻塞)
    :param retry_interval: 每次重复尝试的等待时长
    :return:
    """
    # 建立连接
    # 链接时如果用户名密码不正确不会导致异常
    try:
        # 只是为了让它触发没有通过用户名密码验证的异常
        # 有时候该容器启动比neo4j启动快
        # 在neo4j接受连接前, 循环等待
        while True:
            try:
                graph = Graph(url, user=username, password=password)
                graph.begin().rollback()
                return graph
            except Exception as e:
                from sys import stderr
                stderr.write('exception while connecting: %s\n' % str(e))
                if retry:
                    # 睡眠后继续尝试
                    stderr.write('sleep\n')
                    time.sleep(retry_interval)
                else:
                    raise e
    except AuthError:
        raise Exception("neo4j : Incorrect Username and Password")
